import Storage from "@/common/js/storage";
import * as api from "@/common/api/login";
import {
    getUserPermission
} from "@/common/api/operation";
import {
    getDictDataList
} from "@/common/api/user";
import http, {
    verifyCode
} from "@/common/api/http";
let defUser = {};
const userInfo = Storage.get("userInfo") || defUser;
if (userInfo && typeof userInfo === 'string') {
    try {
        userInfo = JSON.parse(userInfo);
    } catch (err) {}
}

if (!userInfo || !Object.keys(userInfo) || typeof userInfo !== 'object') {
    userInfo = defUser;
}
const token = Storage.get("token") || "";
let sessionKey = Storage.get('sessionKey') || '';
let dictData = Storage.get('dictData') || [];
let permissions = Storage.get('permissions') || [];

export default {
    namespaced: true,
    state: {
        userInfo,
        token,
        dictData,
        sessionKey,
        permissions, //权限列表
    },
    mutations: {
        setUserInfo(state, user = {}) {
            state.userInfo = user;
            Storage.set("userInfo", user);
        },
        setToken(state, data = {
            token: "",
            expire: ""
        }) {
            state.token = data.token;
            http.config.header.Authorization = "Bearer " + data.token;
            Storage.set("token", data.token);
            if (typeof data.expire === 'number') {
                Storage.set("token_expire", new Date().getTime() + data.expire * 3600 * 1000);
            }
        },
        logout(state) {
            state.token = "";
            state.userInfo = {};
            Storage.set("token", "");
            Storage.set("userInfo", {});
            http.config.header.Authorization = "";
            state.permissions = [];
        },
        setPermission(state, data = []) {
            state.permissions = data;
            Storage.set('permissions', data)
        },
        setSessionKey(state, sessionKey) {
            Storage.set("sessionKey", sessionKey);
            state.sessionKey = sessionKey;
        },
        setDictData(state, data = []) {
            data.forEach(i => {
                i.children && i.children.sort((a, b) => a.id - b.id)
            })
            state.dictData = data;
            Storage.set('dictData', data);
        }
    },
    actions: {
        async getUserInfo({
            state,
            commit,
            dispatch
        }, data = {}) {
            let tmp = null;
            let arr = [
                api.getUserInfo(data).then(async res => {
                    if (verifyCode(res.code)) {
                        let user = res.data || {};
                        commit("setUserInfo", user);
                    } else {
                        commit("logout");
                    }
                    tmp = res;
                    return res;
                }).catch(err => {
                    tmp = err;
                    return err;
                }),
                dispatch("getUserPermission")
            ];
            arr.push(dispatch("getDictDataList"))
            await Promise.all(arr)
            return tmp;
        },
        getUserPermission({
            commit
        }) {
            return getUserPermission().then(res => {
                let data = res.data || [];
                commit("setPermission", data);
            }).catch(err => {

            })
        },
        getLoginSession({
            state,
            commit
        }, ) {
            return new Promise((resolve, reject) => {
                uni.login({
                    success: res => {
                        let code = res.code;
                        console.log(code, "?getLoginSession code")
                        resolve(code);
                        commit('setSessionKey', code);
                    },
                    error: err => {
                        console.log(err, "?getLoginSession code err")
                        resolve("");
                    }
                });
            });
        },
        login({
            state,
            commit
        }, Odata = {}, userInfo = {}) {
            return api.login({
                ...Odata,
                ...userInfo
            }).then(res => {
                console.log(res, "?login")
                if (verifyCode(res.code)) {
                    let data = res.data;
                    if (data.token) {
                        commit("setToken", {
                            token: data.token,
                            expire: 1.8
                        });
                    }
                    return res;
                } else {
                    commit("logout");
                    if (Odata && Odata.noShowError) return;
                    uni.showToast({
                        title: res.message || '登录失败',
                        icon: "none"
                    });
                }
                return res;
            }).catch(err => {

            })
        },
        phoneLogin({
            state,
            commit
        }, data = {}) {
            return api.phoneLogin(data).then(res => {
                console.log(res, "??res")
                if (verifyCode(res.code)) {
                    let data = res.data;
                    if (data.token) {
                        commit("setToken", {
                            token: data.token,
                            expire: 1.8
                        });
                        let profile = data.profile || null;
                        if (profile) {
                            commit("setUserInfo", profile);
                        }

                    }
                } else {
                    commit("logout");
                }
                return res;
            }).catch(err => {
                return err;
            })
        },
        getDictDataList({
            commit
        }) {
            return getDictDataList().then(res => {
                if (verifyCode(res.code)) {
                    let data = res.data || [];
                    console.log(data, "??data")
                    commit("setDictData", data);
                }
            }).catch(err => {

            })
        }
    },
    getters: {

    }
}